package com.fingard.dsp.bank.directbank.bos01;

import com.fingard.FGBiz;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.IElecBillQuery;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.*;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.detail.RetAtsB001OperBillQryDetail;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.detail.RetAtsB006BillStateQryDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Map;

public class BOS01ElecBill extends BOS01Base implements IElecBillQuery {

    /**
     * 可操作票据查询
     * 业务类型 1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押 7-出票保证 8-承兑保证 9-背书保证 10-贴现 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
     * 查询类型 1-申请 2-应答 3-撤回
     */
    @Override
    public RetAtsB001OperBillQry D_OperBill_Query_Req(ReqB001OperBillQry query) throws  Exception{
        RetAtsB001OperBillQry retAts=null;
        while (query.readRecord()) {
            if("1".equals(query.detail.queryType)){
                retAts=D_OperBill_Query_Req_1(query);
            }else if("2".equals(query.detail.queryType)){
                retAts=D_OperBill_Query_Req_2(query);
            }else if("3".equals(query.detail.queryType) && "1".equals(query.detail.busiType)){
                retAts=D_OperBill_Query_Req_1(query);
            }else {
                retAts=new RetAtsB001OperBillQry(query.reqHeader);
                retAts.respCode="-1";
                retAts.respInfo="银行暂不支持此撤回操作";
                retAts.writeBefore();
                retAts.writeEnd();
            }
        }
        return retAts;
    }

    /**
     * 通用可操作票据查询 ok
     * @param query
     * @return
     */
    public RetAtsB001OperBillQry D_OperBill_Query_Req_1(ReqB001OperBillQry query){
        RetAtsB001OperBillQry retAts =  new  RetAtsB001OperBillQry(query.reqHeader);
        String respCode ="";
        String respInfo ="";
        retAts.respCode = "0";
        retAts.respInfo  = "";
        retAts.writeBefore();
        try{
            BOS01Header tmpHeader = new BOS01Header();
            tmpHeader.opName = "BillsForOperableQry1_1Op";
            tmpHeader.serialNo = getQryTransID();
            tmpHeader.needSigned = true;
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpHeader);
            xmlWriter.writeElementString("Stdcustacc", query.detail.actNum);//签约账号
            if("3".equals(query.detail.queryType)){
                xmlWriter.writeElementString("Stdqrycont", "04");//查询内容
            }else {
                xmlWriter.writeElementString("Stdqrycont", getBusiType(query.detail.busiType, query.detail.overdueFlag));//查询内容
            }
            xmlWriter.writeElementString("Stdbilltyp", getBillType(query.detail.billType));//票据类型
            xmlWriter.writeElementString("Stdbillnum", "",true);//电子票号
            xmlWriter.writeElementString("Stdbilamtd", query.detail.billAmtDown,true);//票据金额下区间
            xmlWriter.writeElementString("Stdbilamtu", query.detail.billAmtUp,true);//票据金额上区间
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), tmpHeader);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/BOSEBankData/opRep/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/BOSEBankData/opRep/errMsg");
                    //if("0".equals(tmprspcod)){
                        String total=tmpBkReader.getFirstText("/BOSEBankData/opRep/opResult/Stdtotalnm");//总数
                        WriteBankLogLn("银行返回总数据为："+total);
                        if(StringHelper.hasAnyChar(total) && Integer.parseInt(total)>0){
                            int count=0;//循环遍历数
                            while (tmpBkReader.read("/BOSEBankData/opRep/opResultSet/opResult")){
                                RetAtsB001OperBillQryDetail detail = new RetAtsB001OperBillQryDetail();
                                detail.billNo=tmpBkReader.readedXElement.getSingleTextNotNull("Stdbillnum");//电子票据号码
                                detail.billType=getBillType(tmpBkReader.readedXElement.getSingleTextNotNull("Stdbilltyp"));//票据类型 1-银承 2-商承
                                detail.issDate=tmpBkReader.readedXElement.getSingleTextNotNull("Stdissdate");//出票日(yyyy-MM-dd)
                                detail.dueDate=tmpBkReader.readedXElement.getSingleTextNotNull("Stdduedate");//到期日(yyyy-MM-dd)
                                detail.billAmt=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpmmoney");//电子票据金额
                                detail.transFlag=getTransFlag(tmpBkReader.readedXElement.getSingleTextNotNull("Stdendormk"));//背书转让标识 1-可再转让 0-不得转让
                                if("2".equals(query.detail.busiType)){
                                    detail.mustPay="1";//承兑无条件支付委托 1-无条件支付 0-非条件支付
                                }
                                detail.drawName=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrnam");//出票人
                                detail.drawCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrcod");//出票人组织代码
                                detail.drawAct=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwracc");//出票人账号
                                detail.drawBnkName=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrbname");//出票人开户行行名
                                detail.drawBnkCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrbnm");//出票人开户行行号
                                detail.accpName=tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpnam");//承兑人名称
                                detail.accpCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpcod");//承兑人组织代码
                                detail.accpAct=tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpacc");//承兑人账号
                                //detail.accpBnkName=tmpBkReader.readedXElement.getSingleTextNotNull("");//承兑人开户行行名
                                detail.accpBnkCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpbnm");//承兑人开户行行号
                                detail.payeeName=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeenam");//收款人
                                detail.payeeCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeecod");//
                                detail.payeeAct=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeeacc");//收款人账号
                                detail.payeeBnkName=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeebname");//收款人开户行行名
                                detail.payeeBnkCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeebnm");//收款人开户行行号
                                detail.applyDate=DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("Stdappdate"));//申请日期
                                detail.applyName=tmpBkReader.readedXElement.getSingleTextNotNull("Stdappname");//申请人
                                detail.applyCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdappcode");//申请人组织机构代码
                                detail.applyAct=tmpBkReader.readedXElement.getSingleTextNotNull("Stdappacct");//申请人账号
                                detail.applyBnkCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdappbnm");//申请人开户行行号
                                detail.busiNo=tmpBkReader.readedXElement.getSingleTextNotNull("");//交易明细流水
                                detail.busiType=query.detail.busiType;//操作标志
                                detail.queryType=query.detail.queryType;//查询类型
                                detail.memo=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrmem");//备注
                                detail.billStatus=getBillStatus(query.detail.actNum,detail.billNo,query.reqHeader);//票据状态
                                retAts.writeDetail(detail);
                                count++;
                            }
                            WriteBankLogLn("循环解析总数据为："+count);
                            if(count==0){
                                respInfo="符合业务类型的票据为0";
                            }
                        }else if(StringHelper.hasAnyChar(total) && Integer.parseInt(total)==0){
                            respCode="0";
                            respInfo="符合业务类型的票据为0";
                        }else {
                            respCode="-1";
                            respInfo=tmprspmsg;
                        }
                    /*}else {
                        respCode="-1";
                        respInfo=tmprspmsg;
                    }*/
                }else {
                    respCode="-1";
                    respInfo=tmpSbMsg.toString();
                }
            }else {
                respCode="-1";
                respInfo=tmpStrRet[1];
            }
        }catch (Exception e){
            respCode="-1";
            respInfo=e.getMessage();
        }
        if("-1".equals(respCode)){
            retAts = new RetAtsB001OperBillQry(query.reqHeader);
            retAts.respCode = "-1";
            retAts.respInfo  = respInfo;
            retAts.writeBefore();
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 通用签收查询
     * @param query
     * @return
     */
    public RetAtsB001OperBillQry D_OperBill_Query_Req_2(ReqB001OperBillQry query){
        RetAtsB001OperBillQry retAts =  new  RetAtsB001OperBillQry(query.reqHeader);
        String respCode ="";
        String respInfo ="";
        retAts.respCode = "0";
        retAts.respInfo  = "";
        retAts.writeBefore();
        try{
            BOS01Header tmpHeader = new BOS01Header();
            tmpHeader.opName = "BillsForCommonQry1_1Op";
            tmpHeader.serialNo = getQryTransID();
            tmpHeader.needSigned = true;
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpHeader);
            xmlWriter.writeElementString("Stdcustacc", query.detail.actNum);//签约账号
            xmlWriter.writeElementString("Stdbilltyp", getBillType(query.detail.billType));//票据类型
            xmlWriter.writeElementString("Stdorgname", "",true);//发起方名称
            xmlWriter.writeElementString("Stdbilamtd", query.detail.billAmtDown,true);//票据金额下区间
            xmlWriter.writeElementString("Stdbilamtu", query.detail.billAmtUp,true);//票据金额上区间
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), tmpHeader);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/BOSEBankData/opRep/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/BOSEBankData/opRep/errMsg");
                    //if("0".equals(tmprspcod)){
                        String total=tmpBkReader.getFirstText("/BOSEBankData/opRep/opResult/Stdtotalnm");//总数
                    WriteBankLogLn("银行返回总数据为："+total);
                    if(StringHelper.hasAnyChar(total) && Integer.parseInt(total)>0){
                        int count=0;//循环遍历数
                        while (tmpBkReader.read("/BOSEBankData/opRep/opResultSet/opResult")){
                            String stdinfotyp=tmpBkReader.readedXElement.getSingleTextNotNull("Stdinfotyp");//银行签收业务类型
                            String busiType=getStdinfotypByBusiType(query.detail.busiType,query.detail.overdueFlag);//ats签收业务类型转换
                            String billType=query.detail.billType;//ats签收票据类型
                            String stdbilltyp=getBillType(tmpBkReader.readedXElement.getSingleTextNotNull("Stdbilltyp"));///银行签收票据类型
                            if(busiType.equals(stdinfotyp) && stdbilltyp.equals(billType)){
                                RetAtsB001OperBillQryDetail detail = new RetAtsB001OperBillQryDetail();
                                detail.billNo=tmpBkReader.readedXElement.getSingleTextNotNull("Stdbillnum");//电子票据号码
                                detail.billType=stdbilltyp;//票据类型 1-银承 2-商承
                                detail.issDate=tmpBkReader.readedXElement.getSingleTextNotNull("Stdissdate");//出票日(yyyy-MM-dd)
                                detail.dueDate=tmpBkReader.readedXElement.getSingleTextNotNull("Stdduedate");//到期日(yyyy-MM-dd)
                                detail.billAmt=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpmmoney");//电子票据金额
                                detail.transFlag=getTransFlag(tmpBkReader.readedXElement.getSingleTextNotNull("Stdendormk"));//背书转让标识 1-可再转让 0-不得转让
                                detail.mustPay="";//承兑无条件支付委托 1-无条件支付 0-非条件支付
                                detail.drawName=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrnam");//出票人
                                detail.drawCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrcod");//出票人组织代码
                                detail.drawAct=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwracc");//出票人账号
                                detail.drawBnkName=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrbnn");//出票人开户行行名
                                detail.drawBnkCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrbnm");//出票人开户行行号
                                detail.accpName=tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpnam");//承兑人名称
                                detail.accpCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpcod");//承兑人组织代码
                                detail.accpAct=tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpacc");//承兑人账号
                                //detail.accpBnkName=tmpBkReader.readedXElement.getSingleTextNotNull("");//承兑人开户行行名
                                detail.accpBnkCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpbnm");//承兑人开户行行号
                                detail.payeeName=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeenam");//收款人
                                detail.payeeCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeecod");//
                                detail.payeeAct=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeeacc");//收款人账号
                                detail.payeeBnkName=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeebnn");//收款人开户行行名
                                detail.payeeBnkCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeebnm");//收款人开户行行号
                                detail.applyName=tmpBkReader.readedXElement.getSingleTextNotNull("Stdappname");//申请人
                                detail.applyDate=DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("Stdappdate"));//申请日期
                                detail.applyCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdappcode");//申请人机构号
                                detail.applyAct=tmpBkReader.readedXElement.getSingleTextNotNull("Stdappacct");//申请人账号
                                detail.applyBnkCode=tmpBkReader.readedXElement.getSingleTextNotNull("Stdappbnm");//申请人开户行行号
                                detail.payType=getPayType(tmpBkReader.readedXElement.getSingleTextNotNull("Stdstlmthd "));//清算方式
                                //detail.busiNo=tmpBkReader.readedXElement.getSingleTextNotNull("");//交易明细流水
                                detail.busiType=query.detail.busiType;//业务类型
                                detail.queryType=query.detail.queryType;//查询类型
                                detail.memo=tmpBkReader.readedXElement.getSingleTextNotNull("Std400memo");//备注
                                detail.billStatus=getBillStatus(query.detail.actNum,detail.billNo,query.reqHeader);//票据状态
                                retAts.writeDetail(detail);
                                count++;
                            }
                        }
                        WriteBankLogLn("循环解析总数据为："+count);
                        if(count==0){
                            respInfo="符合业务类型的票据为0";
                        }
                    }else if(StringHelper.hasAnyChar(total) && Integer.parseInt(total)==0){
                        respCode="0";
                        respInfo="符合业务类型的票据为0";
                    }else {
                        respCode="-1";
                        respInfo=tmprspmsg;
                    }
                    /*}else {
                        respCode="-1";
                        respInfo=tmprspmsg;
                    }*/
                }else {
                    respCode="-1";
                    respInfo=tmpSbMsg.toString();
                }
            }else {
                respCode="-1";
                respInfo=tmpStrRet[1];
            }
        }catch (Exception e){
            respCode="-1";
            respInfo=e.getMessage();
        }
        if("-1".equals(respCode)){
            retAts = new RetAtsB001OperBillQry(query.reqHeader);
            retAts.respCode = "-1";
            retAts.respInfo  = respInfo;
            retAts.writeBefore();
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 票据操作明细查询 不支持
     */
    @Override
    public RetAtsB002BillTransQry D_B002_BillTrans_Query(ReqB002BillTransQry query) throws  Exception{
        RetAtsB002BillTransQry retAts  = new RetAtsB002BillTransQry(query.reqHeader);
        retAts.respCode="-1";
        retAts.respInfo="暂不支持";
        retAts.writeStart();
        retAts.writeAfter();
        return retAts;
    }

    /**
     * 正面信息查询 ok
     */
    @Override
    public RetAtsB004BillFrontQry D_B004_BillFront_Query(ReqB004BillFrontQry query) throws Exception{
        RetAtsB004BillFrontQry retAts=null;
        while(query.readRecord()){
            retAts=getBillStatuByBillNoAnd04(query.detail.actNum,query.detail.billNo,query.reqHeader);
            if("-1".equals(retAts.respCode) || StringHelper.isNullOrEmpty(retAts.billState)){
                retAts=getBillStatuByBillNoAnd03(query.detail.actNum,query.detail.billNo,query.reqHeader);
            }
        }
        return retAts;
    }

    /**
     * 票据背面信息查询 无
     */
    @Override
    public RetAtsB005BillBackQry D_B005_BillBack_Query(ReqB005BillBackQry query) throws Exception{
        return null;
    }

    /**
     * 票据交易状态查询 ok
     */
    @Override
    public RetAtsB006BillStateQry D_B006_BillState_Qeury(ReqB006BillStateQry query)throws  Exception{
        RetAtsB006BillStateQry retAts  = new RetAtsB006BillStateQry(query.reqHeader);
        RetAtsB006BillStateQryDetail detail=new RetAtsB006BillStateQryDetail();
        retAts.writeStart();
        Connection conn= null;
        try{
            while(query.readRecord()){
                BOS01Header tmpHeader = new BOS01Header();
                tmpHeader.opName = "BillsForInstructStateQry1_1Op";
                tmpHeader.serialNo = getQryTransID();
                tmpHeader.needSigned = true;
                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonHeader(xmlWriter, tmpHeader);
                xmlWriter.writeElementString("Stdtrandat", DateHelper.convertD10toD8(query.detail.operateDate));//原交易日期
                conn=FGBiz.getLocalDbConn();
                Map<String, Object> selMap= JDBCHelper.execQuerySingle(conn,SELECTSEQ,new Object[]{query.detail.reqSeqID,query.reqHeader.bankCode,"8"});
                if(selMap.size()>0){
                    xmlWriter.writeElementString("Stdtrannum", selMap.get("BANKREQSEQID").toString());//原交易流水号
                }else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("业务流水号关联异常");
                    retAts.writeEnd();
                    return retAts;
                }
                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), tmpHeader);
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmprspcod = tmpBkReader.getFirstText("/BOSEBankData/opRep/retCode");
                        String tmprspmsg = tmpBkReader.getFirstText("/BOSEBankData/opRep/errMsg");
                        if("0".equals(tmprspcod)){
                            while (tmpBkReader.read("/BOSEBankData/opRep/opResult")){
                                detail.respCode = "0";//响应码
                                detail.respInfo = tmpBkReader.readedXElement.getSingleTextNotNull("Stdprocinf");//响应信息
                                detail.reqSeqID= query.detail.reqSeqID;//交易流水号
                                detail.billNo = tmpBkReader.readedXElement.getSingleTextNotNull("Stdbillnum");//电子票据号码
                                detail.transState = tmpBkReader.readedXElement.getSingleTextNotNull("Stdtrastat");//处理状态码
                                detail.payInfoCode = detail.transState;//交易信息码
                                detail.billState = getBillStatus(query.detail.actNum,detail.billNo,query.reqHeader);//票据状态
                            }
                        } else{
                            detail.respCode = "-1";
                            detail.respInfo = tmprspmsg;
                        }
                    }else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpBkReader.toString();
                    }
                }else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpStrRet[1];
                }
            }
        }catch (Exception e){
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
        }finally {
            if(conn!=null){
                conn.close();
            }
        }
        retAts.writeDetail(detail);
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 可追索人查询 不支持
     */
    @Override
    public RetAtsB007BillKzsrQry D_B007_BillKzsr_Query(ReqB007BillKzsrQry query) throws Exception{
        RetAtsB007BillKzsrQry retAts=new RetAtsB007BillKzsrQry(query.reqHeader);
        retAts.writeStart();
        retAts.respCode="-1";
        retAts.respInfo="银行暂不支持此操作";
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 历史票据查询 不支持
     */
    @Override
    public RetAtsB008HistoricalBillQry D_B008_HistoricalBillQuery(ReqB008HistoricalBillQry query) throws Exception{
        return null;
    }

    /**
     * 出票登记查询 不支持
     */
    @Override
    public RetAtsB009DrawBillQry D_B009_DrawBillQuery(ReqB009DrawBillQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB010ProtocolStateQry D_B010_ProtocolStateQuery(ReqB010ProtocolStateQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB011TransFlagQry D_B011_TransFlagQuery(ReqB011TransFlagQry query) throws Exception {
        return null;
    }
}
